package com.wyt.common.socket.broad;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.*;

@Component
public class InitHeartBroad implements ApplicationRunner {
    private static Logger logger = LoggerFactory.getLogger(InitHeartBroad.class);

    @Value("${heart.port}")
    private Integer heartPort;

    @Value("${heart.period}")
    private Integer heartPeriod;


    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("=============初始化节点广播(启动定时广播)=============");
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                broad();
            }
        }, 3000, heartPeriod * 1000);
        logger.info("=============初始化广播结束=============");
    }


    public void broad() {
        logger.info("=============本次心跳广播开始===========");
        // 1.创建发送端对象
        try (DatagramSocket socket = new DatagramSocket()) {
            //2、广播信息
            String msg = "";
            DatagramPacket packet = new DatagramPacket(msg.getBytes(), msg.getBytes().length, InetAddress.getByName("255.255.255.255"), heartPort);
            socket.send(packet);
            logger.info("心跳发送结束");
        } catch (Exception e) {
            logger.error("广播异常", e);
        }
        logger.info("=============本次心跳广播结束===========");
    }



}
